package de.gympu.gympulan.core.pluginutil;

import java.util.Iterator;

import org.java.plugin.boot.ApplicationPlugin;
import org.java.plugin.registry.Extension;
import org.java.plugin.registry.ExtensionPoint;

import de.gympu.gympulan.core.GymPuLanImpl;
import de.gympu.gympulan.core.plugins.gplloggingplugin.GPLLogging;

public class PluginLoader<E> {
	
	private ApplicationPlugin base;
	private E[] objects;
	
	private Iterator<?> it;
	
	public PluginLoader(ApplicationPlugin base) {
		this.base = base;
		
		ExtensionPoint toolExtPoint = base.getManager().getRegistry().getExtensionPoint(base.getDescriptor().getId(), "CronJobPlugin");
		it = toolExtPoint.getConnectedExtensions().iterator();
		
	}
	
	public E getNext() {
		if(it.hasNext()) {
			Extension ext = (Extension) it.next();
        	try {
	        	base.getManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
				ClassLoader classLoader = base.getManager().getPluginClassLoader(ext.getDeclaringPluginDescriptor());
				Class<?> toolCls = classLoader.loadClass(ext.getParameter("class").valueAsString());
				E object = (E) toolCls.newInstance();
				
				return object;
        	}
        	catch(Exception e) {
        		throw new PluginLoadException("Fehler beim Laden des Plugins " + ext.getId());
        	}
		}
		
		return null;
	}
	
	public boolean hasNext() {
		return it.hasNext();
	}
}
